package com.nulldev.util.networking.misc;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.data.Variables;
import com.nulldev.util.io.IOUtils;

public class SocketUtil {

	public static void printSocketOptions(final Socket sock) throws Exception {
		Variables.requireNonNull(sock, "sock");
		JVM.println(sock);
		JVM.println("\tRCV_BUF: " + sock.getReceiveBufferSize());
		JVM.println("\tSND_BUF: " + sock.getSendBufferSize());
		JVM.println("\tSO_LINGER: " + sock.getSoLinger());
		JVM.println("\tSO_TIMEOUT: " + sock.getSoTimeout());
		JVM.println("\tIP_TOS: " + sock.getTrafficClass());
		JVM.println("\tSO_KEEP_ALIVE: " + sock.getKeepAlive());
		JVM.println("\tSO_OOB_INLINE: " + sock.getOOBInline());
		JVM.println("\tSO_REUSE_ADDR: " + sock.getReuseAddress());
		JVM.println("\tSO_NO_DELAY: " + sock.getTcpNoDelay());
	}

	public static int getRecieveBufferSize(final Socket socket) {
		try {
			return socket.getReceiveBufferSize();
		} catch (SocketException e) {
			return IOUtils.MEMORY_ALLOC_BUFFER;
		} catch (NullPointerException e) {
			return -1;
		}
	}

	public static int getSendBufferSize(final Socket socket) {
		try {
			return socket.getSendBufferSize();
		} catch (SocketException e) {
			return IOUtils.MEMORY_ALLOC_BUFFER;
		} catch (NullPointerException e) {
			return -1;
		}
	}

	public static String getIPHostName(final SocketAddress remoteAddress) {
		if (remoteAddress == null)
			return null;
		return ((InetSocketAddress) remoteAddress).getHostString();
	}

}
